const http = require('http');
const path = require('path');
const server = http.createServer();

server.listen(3000, () => console.log('图书借口服务启动成功'));
server.on('request', (req, res) => {
    let url = req.url;
    let method = req.method;
    if (method == 'GET' && url === '/api/getbooks') {
        let books = require(path.join(__dirname, 'book.json'));
        res.setHeader('Content-Type', 'application/json;chartset=utf-8');
        let result = {
            status: 200,
            msg: '获取成功',
            data: books,
        }
        res.end(JSON.stringify(result));

    } else if (method == 'GET' && url == '/api/delbook') {
        let books = require(path.join(__dirname, 'book.json'));
        res.setHeader('Content-Type', 'application/json;chartset=utf-8');
        let id = req.url.replace(/\D/g, '');
        let result = books.filter(item => item.id != id);
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        // 把过滤后的结果，存放到books.json中即可
        fs.writeFile(path.join(__dirname, 'books.json'), JSON.stringify(result), err => {
            if (err) {
                console.log(err);
                res.end(JSON.stringify({ status: 400, msg: '删除失败' }));
            } else {
                res.end(JSON.stringify({ status: 200, msg: '删除成功' }));
            }
        });

    } else if (method == 'POST' && url === '/api/addbook') {

    } else {
        res.writeHead(404, {
            'Content-Type': 'text/html;charset=utf-8'
        });
        res.end('小朋友，你走错路了');
    }
})